//
//  ViewController.m
//  19-JSON网易
//
//  Created by GivenBmli on 16/8/9.
//  Copyright © 2016年 GivenBmli. All rights reserved.
//

#import "ViewController.h"
#import "BM-CollectionViewLayout.h"
#import "NewsTitle.h"
#import "NewsTitleCollectionViewCell.h"
@interface ViewController ()<UICollectionViewDelegate , UICollectionViewDataSource,BM_LayoudDelget>
@property (weak, nonatomic) IBOutlet UICollectionView *myColectionView;
@property (nonatomic ,strong)NSMutableArray <NewsTitle *>* newsTitleArray;
@end

@implementation ViewController

- (void)viewDidLoad {
    self.newsTitleArray = [NSMutableArray array];
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    [self handelData];
    BM_CollectionViewLayout *title = (BM_CollectionViewLayout *)self.myColectionView.collectionViewLayout;
    title.delegate = self;
    
}

- (void)handelData {
  NSString *newsJSON = [[NSBundle mainBundle] pathForResource:@"news" ofType:@"json"];
    NSData *JSONData = [NSData dataWithContentsOfFile:newsJSON];
//    JSON解析
    NSError *error = nil;
   NSDictionary *newsTitleDic =  [NSJSONSerialization JSONObjectWithData:JSONData options:NSJSONReadingMutableContainers error:&error];
    NSArray *list = newsTitleDic[@"tList"];
    for (NSDictionary *newsTitle in list) {
        
        NewsTitle *news = [NewsTitle newsTitle:newsTitle];
        [_newsTitleArray addObject:news];
        
    }
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout widthForItemAtIndexPath:(NSIndexPath *)indexPath height:(CGFloat)height {
    NewsTitle *titles = _newsTitleArray[indexPath.row];
   CGRect newRect = [titles.tname boundingRectWithSize:CGSizeMake(CGFLOAT_MAX, CGRectGetHeight(self.view.bounds)) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:17]}  context:nil];
    CGFloat with = ceilf(CGRectGetWidth(newRect));
    
    return with;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    NewsTitleCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"return" forIndexPath:indexPath];
    
    cell.newsTitle = _newsTitleArray[indexPath.row];
    return cell;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return _newsTitleArray.count;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
